<template>
	<div class="user-add" v-loading="loading">
		<div class="form-add">
			<el-form ref="temp" :model="temp" :rules="rules" size="small" label-width="100px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="账号" prop="account">
							<el-input
								ref="account"
								v-model="temp.account"
								placeholder="请输入登陆账号，推荐使用邮箱或手机号注册账号"
								:disabled="!addOrEdit"
								@blur="verifyAccount"
							></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="addOrEdit">
						<el-form-item label="密码" prop="password">
							<el-input v-model="temp.password" show-password autocomplete="new-password" :placeholder="passwordTips"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="addOrEdit">
						<el-form-item label="确认密码" prop="confirmPassword">
							<el-input v-model="temp.confirmPassword" show-password :placeholder="passwordTips2"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="!isEdit ? 12 : 24">
						<el-form-item label="姓名" prop="userName">
							<el-input v-model="temp.userName" autocomplete="off" placeholder="请输入姓名"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!isEdit">
						<el-form-item label="选择部门" class="top_unit" prop="deptId">
							<el-popover placement="bottom-start" v-model="treeFlag" class="orgTree" trigger="click">
								<el-tree
									:data="deptData"
									:props="defaultProps"
									:expand-on-click-node="false"
									node-key="id"
									style="width: 400px"
									@node-click="handleNodeClickDep"
								></el-tree>
								<el-input slot="reference" ref="input" v-model="treeName" clearable :readonly="true" style="width: 100%" placeholder="请选择部门"></el-input>
							</el-popover>
							<i @click.stop="closeName" class="el-icon-circle-close" v-if="treeName"></i>
							<i class="el-icon-arrow-down" v-else></i>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="!isHomePage && !isEdit">
						<el-form-item label="选择角色" prop="roleIds">
							<el-select style="width: 100%" v-model="temp.roleIds" multiple placeholder="请选择角色" size="small">
								<el-option v-for="(v, i) in roleData" :key="i" :label="v.name" :value="v.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="!isEdit ? 12 : 24">
						<el-form-item label="电话"><el-input v-model="temp.phone" placeholder="请输入电话"></el-input></el-form-item>
					</el-col>
					<el-col :span="!isEdit ? 12 : 24">
						<el-form-item label="职务" prop="duty"><el-input v-model="temp.duty" placeholder="请输入职务"></el-input></el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<ImgCropper ref="ImgCropper" :props="propsConfig" @e-emit="setCoverImg" />
		</div>
		<div class="btn-submit" v-show="page != 'homePage'">
			<el-button type="primary" size="small" v-preventReClick @click="submitForm('temp')">提 交</el-button>
			<el-button class="btn-back" size="small" @click="handleBack">返回</el-button>
		</div>
	</div>
</template>
<script>
import eduData from '../common/eduData';
import rules from '../mixin/rules';
export default {
	mixins: [rules],
	components: {
		ImgCropper: () => import('@/components/imgCropper')
	},
	data() {
		return {
			isHomePage: false,
			temp: {
				account: '',
				isLeader: '1',
				idType: '1',
				sex: '1',
				deptId: '',
				type: '',
				roleIds: []
			},
			deptData: this.$store.state.tbSysDept.deptList || [],
			roleData: this.$store.state.tbSysRole.roleList || [],
			typeData: [],
			addOrEdit: true,
			defaultProps: {
				children: 'childList',
				label: 'name'
			},
			treeFlag: false,
			treeName: '',
			passwordTips: '请输入密码',
			passwordTips2: '请输入确认密码',
			eduData,
			loading: false,
			focusFlag: false,
			propsConfig: {
				defaultValue: null,
				type: 4, //1. 文章封面 2. 书籍封面
				button: ['upload', 'fromNetDisk']
			}
		};
	},
	props: ['userId', 'page', 'pageFlag'],
	computed: {
		ueWidth() {
			return this.$store.getters.windowWidth > 1400 ? 820 : 700;
		},
		isEdit() {
			return this.$route.query.action;
		}
	},
	watch: {
		userId: {
			immediate: true,
			handler(val) {
				this.init(val);
				if (!this.roleData.length) {
					this.getRoleData();
				}
				if (!this.deptData.length) {
					this.getDeptList();
				}
			}
		}
	},
	mounted() {
		this.isHomePage = this.pageFlag;
		this.$bus.$on('submitUpdateUserInfo', () => {
			this.submitForm('temp');
		});
	},
	beforeDestroy() {
		this.$bus.$off('submitUpdateUserInfo');
	},
	methods: {
		init(userId) {
			this.addOrEdit = !userId;
			this.queryUserType();
			this.getUserData(userId);
		},
		async getUserData(userId) {
			if (this.addOrEdit) return;
			this.loading = true;
			let res = await this.$store.dispatch('queryTbUserById', userId);
			this.temp = JSON.parse(JSON.stringify(res.data[0]));
			let roleIds = this.temp.hasOwnProperty('menuRoleList') ? this.temp.menuRoleList.map((v) => v.id) : [];
			this.$set(this.temp, 'roleIds', roleIds);
			this.propsConfig.defaultValue = !this.temp.sysAttachment ? '' : this.temp.sysAttachment.httpUrl;
			this.treeName = this.temp.deptName;
			this.loading = false;
		},
		//查询部门
		async getDeptList() {
			let res = await this.$store.dispatch('queryTbDeptList', { pId: '0' });
			this.deptData = res.data;
			this.$store.commit('SET_Dept', this.deptData);
		},
		//获取角色数据
		async getRoleData() {
			let obj = {
				page: 1,
				limit: 99,
				type: 1
			};
			let res = await this.$store.dispatch('queryTbRoleList', obj);
			this.roleData = res.data;
			this.$store.commit('SET_Role', this.roleData);
		},
		// 清空单位
		closeName() {
			this.treeName = '';
			this.temp.deptId = '';
		},
		// 选中上一级单位
		handleNodeClickDep(val) {
			this.treeName = val.name;
			this.treeFlag = false;
			this.temp.deptId = val.id;
		},
		//查询用户类型
		async queryUserType() {
			this.typeData = await this.$store.dispatch('getDictionaryEnumListVal', 'TB_SYS_USER_TYPE');
		},
		handleBack() {
			if (this.$route.fullPath !== '/admin/system/user-manage') {
				this.$router.back();
			}
			this.$bus.$emit('changeUserTemplate', 'Layout');
			this.$bus.$emit('showUserSetting', false);
		},
		// 提交
		async submitForm(form) {
			this.$refs[form].validate((valid) => {
				if (valid) {
					this.addOrEdit ? this.add() : this.edit();
				}
			});
		},
		//验证账号是否存在
		async verifyAccount() {
			let { id, account } = this.temp;
			if (!account) return;
			let res = await this.$store.dispatch('verifyTbUser', { id, account });
			if (res.msg != 0) {
				this.warnMsg('账号已存在');
			}
			return res.msg == 0;
		},
		//新增
		async add() {
			let valid = await this.verifyAccount();
			if (!valid) return;
			this.$delete(this.temp, 'confirmPassword');
			await this.$store.dispatch('addTbUser', this.temp);
			this.handleBack();
		},
		//修改
		async edit() {
			await this.$store.dispatch('updateTbUser', this.temp);
			this.handleBack();
		},

		//选择头像
		setCoverImg(data) {
			let { id, httpUrl, minHttpUrl } = data;
			this.temp.attachmentId = id;
			this.propsConfig.defaultValue = minHttpUrl || httpUrl;
		}
	}
};
</script>

<style lang="scss" scoped>
.user-add {
	.form-add {
		display: flex;
		align-items: flex-start;
		position: relative;
		background-color: #fff;
		overflow: auto;
		padding-top: 20px;
		.el-form-item.top_unit i.el-icon-circle-close,
		.el-form-item.top_unit i.el-icon-arrow-down {
			position: absolute;
			right: 10px;
			top: 10px;
			cursor: pointer;
			color: #c0c4cc;
		}
		form.el-form {
			width: 800px;
			margin-right: 30px;
		}
		.el-select {
			width: 100%;
		}
		.el-col-12 {
			height: 54px;
			overflow: hidden;
		}
	}
	.btn-submit {
		padding-left: 100px;
		box-sizing: border-box;
	}
}
</style>
